<template>
  <view class="baseForm">
    <view class="overhidden">
      <view>
        <u--form
          labelPosition="top"
          :model="formData"
          :rules="rules"
          labelWidth="300"
          ref="uForm"
          class="form"
          errorType="toast"
        >
          <view
            v-show="!taskInfo?.id && loading === false"
            class="flex justify-center font-14"
            style="margin: 30px 0 30px 0"
          >
            暂无模具信息，请录入模具编号
          </view>
          <u-loading-icon
            class="flex justify-center mt-20"
            textSize="18"
            v-show="loading"
          ></u-loading-icon>
          <!-- 模具详情 -->
          <!-- <ConsumablesDetachInfo v-if="taskInfo.id" :taskInfo="taskInfo"></ConsumablesDetachInfo> -->

          <view class="detail card">
            <view class="flex flex-col justify-between flex-1 h-full">
              <view class="record-content">
                <view
                  class="flex title justify-between"
                  @click="() => (isCollapse = !isCollapse)"
                >
                  <text>模具信息</text>
                  <u-icon
                    v-show="!isCollapse && taskInfo?.id"
                    name="arrow-up"
                    color="#000a7b"
                  ></u-icon>
                  <u-icon
                    v-show="isCollapse && taskInfo?.id"
                    name="arrow-down"
                    color="#000a7b"
                  ></u-icon>
                </view>
                <view
                  class="record-item"
                  @click="() => (isCollapse = !isCollapse)"
                >
                  <!-- <text style="min-width: 73px">模具状态</text>
                  <view class="flex" style="flex-wrap: nowrap">
                    <text>
                      {{
                        useDictionaryStore().filterDictName(
                          "MouldStatus",
                          taskInfo.assetStatus ?? ""
                        )
                      }}
                    </text>
                  </view> -->
                  <text style="min-width: 73px">模具编号</text>
                  <text>{{ taskInfo?.mouldCode || "" }}</text>
                </view>
                <view v-show="!isCollapse && taskInfo?.id">
                  <view class="record-item">
                    <text style="min-width: 73px">模具名称</text>
                    <text>{{ taskInfo?.mouldName || "" }}</text>
                  </view>
                  <view class="record-item">
                    <text>模具类型</text>
                    <text>{{ taskInfo?.mouldType || "" }}</text>
                  </view>
                  <view class="record-item">
                    <text>模具位置</text>
                    <text>{{ taskInfo?.locationName || "" }}</text>
                  </view>
                </view>
              </view>
            </view>
          </view>

          <!-- 点检详情 -->
          <view
            class="plan card record-content"
            style="margin-bottom: 70px"
            v-if="taskInfo.id"
          >
            <view
              v-show="
                !taskInfo?.listCheckOrder[0]?.details ||
                taskInfo?.listCheckOrder[0]?.details.length === 0
              "
              class="flex justify-start grey-color"
              style="margin: 12px 0 10px"
            >
              暂无模具点检信息
            </view>
            <view
              class=""
              v-for="(item1, index1) in taskInfo?.listCheckOrder"
              :key="index1"
            >
              <view class="record-content">
                <view
                  v-show="
                    item1?.details == null || item1?.details?.length === 0
                  "
                  class="flex justify-center font-14"
                  style="margin: 30px 0 30px 0"
                >
                  暂无点检信息!
                </view>

                <view
                  class="overhidden"
                  v-for="(item, index) in item1?.details"
                  :key="index"
                >
                  <view>
                    <view class="record-content">
                      <view class="record-item">
                        <view class="title_new">
                          {{ item?.sopItemName || "" }}
                          <u-icon
                            v-if="
                              item?.sopItem.sopItemMethod ||
                              item?.itemImages?.length > 0
                            "
                            name="more-circle-fill"
                            color="rgb(192, 196, 204)"
                            size="18"
                            @click="openInfoModal(item)"
                          ></u-icon>
                        </view>
                        <view
                          :class="item?.sopItemResult == 0 ? 'ce45656' : ''"
                          style="min-width: 50px"
                        >
                          {{ item?.sopItemResult == 0 ? "不合格" : "合格" }}
                        </view>
                      </view>
                      <view
                        class="record-item"
                        v-if="
                          item.sopItem.standardValue == 1 &&
                          !(
                            !item.sopItem.standardMinValue &&
                            !item.sopItem.standardMaxValue
                          )
                        "
                      >
                        <text>上下限值</text>
                        <text
                          v-if="
                            item?.sopItem.standardMinValue !==
                            item?.sopItem.standardMaxValue
                          "
                        >
                          {{ item?.sopItem.standardMinValue || "" }}-{{
                            item?.sopItem.standardMaxValue || ""
                          }}{{ item?.standardValueUnit || "" }}
                        </text>
                        <text v-else>
                          {{ item?.sopItem.standardMinValue || ""
                          }}{{ item?.sopItem.standardValueUnit || "" }}
                        </text>
                      </view>
                      <view
                        class="record-item"
                        v-if="item.sopItem.standardValue == 1"
                      >
                        <view class="flex">
                          实际值
                          <text
                            class="require_icon"
                            v-if="item?.sopItem.sopExecute == '1'"
                          >
                            *
                          </text>
                        </view>
                        <u-input
                          v-if="props.isRead == 0"
                          v-model="item.sopItemValue"
                          placeholder="请输入"
                          class="minInput"
                          :class="
                            sizeColorHandle(
                              item.sopItemValue,
                              item?.sopItem.standardMinValue,
                              item?.sopItem.standardMaxValue
                            )
                          "
                          @change="
                            computedResult(
                              item,
                              item.sopItemValue,
                              item?.sopItem.standardMinValue,
                              item?.sopItem.standardMaxValue
                            )
                          "
                          inputAlign="right"
                          border="none"
                        ></u-input>
                        <image
                          v-if="props.isRead == 0"
                          @click.stop="clearInputData(index1, index)"
                          v-show="item.sopItemValue"
                          src="@/static/image/delete.png"
                          class="deleteIcon"
                        />
                        <text
                          v-else
                          :class="
                            sizeColorHandle(
                              item.sopItemValue,
                              item?.sopItem.standardMinValue,
                              item?.sopItem.standardMaxValue
                            )
                          "
                        >
                          {{ item.sopItemValue || "" }}
                        </text>
                      </view>
                      <view
                        class="record-item"
                        v-if="item.sopItem.standardValue == 2"
                      >
                        <view class="flex">
                          <view style="display: flex; align-items: center"
                            >实际值<text
                              class="require_icon"
                              v-if="item?.sopItem.sopExecute == '1'"
                              >*</text
                            >：</view
                          >
                          <!-- :disabled="props.isRead == 1" -->
                          <u-radio-group
                            v-model="item.sopItemValueId"
                            :disabled="props.isRead == 1 ? true : false"
                            @change="
                              (e) => changeDataRadio(e, item, index1, index)
                            "
                          >
                            <u-radio
                              :customStyle="{
                                marginRight: '20px',
                                fontSize: '14px',
                              }"
                              shape="square"
                              v-for="(self, index2) in item.sopItem.details"
                              :key="index2"
                              :label="self.standardValue"
                              :name="self.id"
                            ></u-radio>
                          </u-radio-group>
                        </view>
                        <!-- <view class="flex">
												实际值
												<text class="require_icon" v-if="item?.sopItem.sopExecute == '1'">*</text>
											</view>
											<view @click="hideKeyboard1(index1, index, item.sopItem.details ?? [])" class="flex input-box">
												<u-input
													v-model="item.sopItemValue"
													border="none"
													placeholder="请选择"
													readonly
													class="minInput"
													:class="sizeColorHandle1(item.sopItemValueId, item.sopItem.details ?? [])"
												></u-input>
												<image @click.stop="clearData(index1, index)" v-show="item.sopItemValueId" src="@/static/image/delete.png" class="deleteIcon" />
											</view> -->
                      </view>

                      <view
                        class="record-item"
                        v-if="
                          item.sopItem.standardValue == 2 &&
                          item?.sopItemResult == 0
                        "
                      >
                        <view class="flex">
                          <view style="display: flex; align-items: center"
                            >异常位置：</view
                          >
                          <u-radio-group
                            v-model="item.abnormalLocation"
                            class="error-place-radio"
                            :disabled="props.isRead == 1 ? true : false"
                          >
                            <u-radio
                              :customStyle="{
                                marginRight: '10px',
                                fontSize: '14px',
                              }"
                              shape="square"
                              v-for="(
                                item, index
                              ) in useDictionaryStore().filterDictList(
                                'abnormalLocation'
                              )"
                              :key="index"
                              :label="item.label"
                              :name="item.value"
                            ></u-radio>
                          </u-radio-group>
                        </view>
                      </view>
                    </view>
                    <!-- 待需要上传图片后启用 -->
                    <view class="mt-8 flex" v-if="item.sopItem.sopImage == '1'">
                      <upload-image
                        :multiple="false"
                        :key="index"
                        :keys="index"
                        @fileChange="(list) => getImages(list, index1, index)"
                        :list="item.images ?? []"
                        :capture="capture"
                        :isRead="props.isRead == 1 ? true : false"
                      ></upload-image>
                    </view>
                  </view>
                  <u-divider
                    v-show="index + 1 !== item1?.details.length"
                  ></u-divider>

                  <!-- 查看页面并且没有现场图片则不展示 -->
                  <!-- <view>
											<view class="title flex justify-between">
												<text class="mt-4">现场图片</text>
											</view>
							
											<view class="mt-8">
												<view class="mt-8 flex">
													<upload-image :multiple="false" :keys="4545" @fileChange="getSceneImages" :list="taskInfo.images ?? []" :capture="capture"></upload-image>
												</view>
											</view>
										</view> -->
                </view>
              </view>
              <!-- 提交 -->
              <view v-if="props.isRead != 1" class="submit_btn_divTwo">
                <button type="default" class="grey_btnTwo" @click="resetFields">
                  重 置
                </button>
                <button
                  type="primary"
                  :disabled="postLoading"
                  :loading="postLoading"
                  @click="submit"
                  class="submit_btnTwo"
                >
                  确认点检
                </button>
              </view>
            </view>

            <!-- 查看页面并且没有现场图片则不展示 -->
            <!-- <view>
							<view class="title flex justify-between">
								<text class="mt-4">现场图片</text>
							</view>

							<view class="mt-8">
								<view class="mt-8 flex">
									<upload-image :multiple="false" :keys="4545" @fileChange="getSceneImages" :list="taskInfo.images ?? []" :capture="capture"></upload-image>
								</view>
							</view>
						</view> -->
          </view>
          <view v-if="props.isRead != 1" style="height: 50px"></view>
        </u--form>
      </view>
    </view>
    <!-- 实际值选择picker -->
    <u-picker
      :show="showPicker"
      :defaultIndex="defaultIndex"
      :columns="currentColumns"
      keyName="text"
      immediateChange
      @cancel="showPicker = false"
      @confirm="changeData"
    ></u-picker>
    <u-modal :show="showInfo" @confirm="showInfo = false">
      <view class="" style="word-break: break-word">
        <view class="">
          作业工具：{{ contentInfo?.sopItem?.sopItemMethod ?? "" }}
        </view>
        <view
          v-if="contentInfo?.sopItem?.sopItemTool"
          style="word-break: break-all; margin-top: 7px"
        >
          作业方法：{{ contentInfo?.sopItem?.sopItemTool ?? "" }}
        </view>
        <view class="flex">指导书</view>
        <uploadFileDetail
          :multiple="false"
          :keys="4545"
          :list="contentInfo.itemImages ?? []"
          :capture="capture"
        ></uploadFileDetail>
      </view>
    </u-modal>
  </view>
</template>

<script lang="ts" setup>
import { ref, reactive, toRaw } from "vue";
import { http } from "@/utils/http";
import { mockData } from "./index";
import { onPageScroll, onShow, onLoad } from "@dcloudio/uni-app";
import UploadImage from "@/components/upload-image-ssr.vue";
import ScanBar from "@/components/scan-bar/index.vue";
import ConsumablesDetachInfo from "@/pages/eam/mold/enterWarehouse/components/info.vue";
import { sizeColorHandle1, sizeColorHandle } from "@/utils/common";
import uploadFileDetail from "@/components/upload-file-detail.vue";
import { toScanCode } from "@/components/hs-scancode/scan.js";
import router from "../../../../utils/router";
import { useDictionaryStore } from "@/stores/useDictionaryStore";
import { useEamStore } from "@/stores/useEamStore";
// 刚进来 页面置顶
onLoad(() => {
  uni.pageScrollTo({
    scrollTop: 0,
    duration: 0,
  });
});

onShow(() => {
  props.mouldId && getDeviceInfo();
});

const props = defineProps({
  mouldId: {
    type: String,
    default: () => "",
  },
  mouldCode: {
    type: String,
    default: () => "",
  },
  isRead: {
    type: String,
    default: "0", // 1是查看
  },
  mouldType: {
    type: String,
    default: () => "",
  },
});

// 是否折叠
const isCollapse = ref(false);

// 作业方法提示框
const showInfo = ref(false);
const contentInfo = ref("");
function openInfoModal(data) {
  // showInfo.value = true;
  // contentInfo.value = JSON.parse(JSON.stringify(data))
  useEamStore().setGuideBookData(data);
  uni.navigateTo({
    url: `/pages/eam/mold/enterWarehouse/guideBook`,
    fail: () => {
      uni.showToast({
        title: "敬请期待",
        icon: "error",
      });
    },
  });
}

/**
 * 选择实际值
 */
const showPicker = ref(false);
const currentColumns = reactive([[]]);
const currentIndex = ref();
const currentIndex1 = ref();
const defaultIndex = ref([0]);

/**
 * 组织键盘弹出
 */
function hideKeyboard(index1, index, list) {
  console.log("hideKeyboard", index1, index, list);
  const lists = JSON.parse(JSON.stringify(list));
  lists.forEach((item) => {
    item.text = `${item.standardValue} - ${
      item.resultValue == "1" ? "正常" : "异常"
    }`;
  });
  currentIndex.value = index;
  currentIndex1.value = index1;
  currentColumns[0] = lists ?? [];
  // 给原有的值,赋值picker默认index
  const sopItemValueId =
    taskInfo.value.listCheckOrder[index1].details[index].sopItemValueId;
  if (sopItemValueId) {
    const currentIndex = list.findIndex((self) => self.id === sopItemValueId);
    defaultIndex.value = [currentIndex];
  } else {
    defaultIndex.value = [0];
  }
  showPicker.value = true;
  uni.hideKeyboard();
}
function clearData(index1, index) {
  taskInfo.value.listCheckOrder[index1].details[index].sopItemValueId = "";
  taskInfo.value.listCheckOrder[index1].details[index].sopItemValue = "";
  showPicker.value = false;
}
function clearInputData(index1, index) {
  taskInfo.value.listCheckOrder[index1].details[index].sopItemValue = "";
}
function changeData(e) {
  taskInfo.value.listCheckOrder[currentIndex1.value].details[
    currentIndex.value
  ].sopItemValue = e.value[0].standardValue;
  taskInfo.value.listCheckOrder[currentIndex1.value].details[
    currentIndex.value
  ].sopItemValueId = e.value[0].id;
  taskInfo.value.listCheckOrder[currentIndex1.value].details[
    currentIndex.value
  ].sopItemResult = e.value[0].resultValue;
  showPicker.value = false;
}

function changeDataRadio(e, item, currentIndex1, currentIndex) {
  console.log("changeDataRadio", e, item);
  const current = item.sopItem.details.filter((self) => self.id === e)[0];
  if (current) {
    // 合格时异常位置置为空/不合格时给默认值
    if (current.resultValue == 1) {
      taskInfo.value.listCheckOrder[currentIndex1].details[
        currentIndex
      ].abnormalLocation = "";
    } else {
      taskInfo.value.listCheckOrder[currentIndex1].details[
        currentIndex
      ].abnormalLocation = "0";
    }
    taskInfo.value.listCheckOrder[currentIndex1].details[
      currentIndex
    ].sopItemValue = current.standardValue ?? "";
    taskInfo.value.listCheckOrder[currentIndex1].details[
      currentIndex
    ].sopItemValueId = current.id ?? "";
    taskInfo.value.listCheckOrder[currentIndex1].details[
      currentIndex
    ].sopItemResult = current.resultValue ?? "";
  }
}

function computedResult1(item, id, list) {
  if (list.length) {
    const current = list.filter((item) => item.id === id)[0] || null;
    console.log("current", current);
    if (!current) {
      item.sopItemResult = "1";
      return;
    } else if (current.resultValue != "1") {
      item.sopItemResult = "0";
      return;
    } else {
      item.sopItemResult = "1";
      return;
    }
  }
  return "";
}
function computedResult(item, number, minNumber, maxNumber) {
  console.log("computedResult", item, number, minNumber, maxNumber);
  if (!number) {
    item.sopItemResult = "1";
    return;
  }
  if (!minNumber && !maxNumber) {
    item.sopItemResult = "1";
    return;
  }
  if (isNaN(Number(number))) {
    item.sopItemResult = "0";
    return;
  }
  if (minNumber === maxNumber && Number(number) != Number(minNumber)) {
    item.sopItemResult = "0";
    return;
  }
  if (minNumber != maxNumber && Number(number) < Number(minNumber)) {
    item.sopItemResult = "0";
    return;
  }
  if (minNumber != maxNumber && Number(number) > Number(maxNumber)) {
    item.sopItemResult = "0";
    return;
  }
  item.sopItemResult = "1";
}

// 表单详情
let formData = reactive({
  consumeCode: "",
});

// 初始化页面，获取检查详情
let taskInfo = ref<any>({});
const loading = ref(false);

// 表单规则定义
const rules = ref({});

// 摄像头参数设置
const capture = ref(["camera", "album"]);
// 获取图片
function getImages(list, index1, index) {
  const current = JSON.parse(
    JSON.stringify(taskInfo.value.listCheckOrder[index1].details)
  )[index];
  current.images = [];
  list?.forEach((item) => {
    current.images.push(item);
  });
  const elder = JSON.parse(
    JSON.stringify(taskInfo.value.listCheckOrder[index1].details)
  );
  elder[index] = current;
  taskInfo.value.listCheckOrder[index1].details = elder;
}

// 获取现场图片
function getSceneImages(list) {
  taskInfo.value.images = list;
}

// form信息重置
function resetData() {
  props.mouldId && getDeviceInfo();
  uni.pageScrollTo({
    scrollTop: 0,
    duration: 100,
  });
}

function resetFields() {
  // resetData();
  taskInfo?.value?.listCheckOrder[0].details?.forEach((item) => {
    item.sopItemValue = "";
  });
}

// 校验提交
const uForm = ref();
const postLoading = ref(false);
async function submit() {
  console.log(taskInfo.value);
  // 校验是否录入模具编号成功
  if (!taskInfo.value.id) {
    uni.showToast({
      title: "请录入正确的信息",
      icon: "none",
    });
    return false;
  }

  console.log("taskInfo.value", taskInfo.value);

  // 判断测量值是否是数字
  for (let i = 0; i < taskInfo.value.listCheckOrder.length; i++) {
    for (
      let j = 0;
      j < taskInfo.value?.listCheckOrder[i]?.details.length;
      j++
    ) {
      if (
        taskInfo.value.listCheckOrder[i]?.details[j]?.sopItem.standardValue ==
        "1"
      ) {
        if (
          isNaN(
            Number(taskInfo.value.listCheckOrder[i]?.details[j]?.sopItemValue)
          )
        ) {
          uni.showToast({
            title: `${taskInfo.value.listCheckOrder[i].details[j].sopItemName}的实际值只能为数字`,
            icon: "none",
          });
          return false;
        }
      }
    }
  }

  // 判断必填项是否为空
  for (let i = 0; i < taskInfo.value.listCheckOrder.length; i++) {
    for (
      let j = 0;
      j < taskInfo.value?.listCheckOrder[i]?.details.length;
      j++
    ) {
      if (
        taskInfo.value.listCheckOrder[i]?.details[j]?.sopItem.sopExecute ==
          "1" &&
        !taskInfo.value.listCheckOrder[i]?.details[j]?.sopItemValue
      ) {
        uni.showToast({
          title: `${taskInfo.value.listCheckOrder[i].details[j].sopItemName}的实际值不能为空`,
          icon: "none",
        });
        return false;
      }
	  
	  const images1 = taskInfo.value.listCheckOrder[i]?.details[j]?.images
	  if (
	  	taskInfo.value.listCheckOrder[i]?.details[j]?.sopItem.sopImage == "1" && taskInfo.value.listCheckOrder[i]?.details[j]?.sopItem.sopExecute ==
	  	"1" && (images1?.length==0 || !images1)
	  ) {
	  	uni.showToast({
	  		title: `${taskInfo.value.listCheckOrder[i].details[j].sopItemName}的图片不能为空`,
	  		icon: "none",
	  	});
	  	return false;
	  }
    }
  }

  // 计算是否合格
  const listCheckOrder: any = taskInfo.value.listCheckOrder;
  for (let i = 0; i < listCheckOrder.length; i++) {
    taskInfo.value.passStatus = 1;
    const details = listCheckOrder[i]?.details;
    for (let j = 0; j < details.length; j++) {
      if (details[j]?.sopItemValue && details[j].sopItemResult == "0") {
        taskInfo.value.passStatus = 0;
      }
    }
  }

  // save提交
  postLoading.value = true;
  const result: any = await http({
    method: "POST",
    url: `/eam/mouldAssetInfo/saveSpotCheckOut`,
    data: toRaw(taskInfo.value),
  }).catch(() => {
    postLoading.value = false;
  });
  if (result?.code == 200) {
    uni.showToast({
      title: "提交成功",
    });
    setTimeout(() => {
      postLoading.value = false;
      uni.navigateBack();
    }, 500);
  }
}

// 获取模具信息（接口请求）
async function getDeviceInfo() {
  // taskInfo.value = JSON.parse(JSON.stringify(mockData));
  loading.value = true;
  const data: any = await http({
    method: "POST",
    url: `/eam/mouldAssetInfo/getCheckOrderOut`,
    data: { mouldType: props.mouldType, id: props.mouldId },
  }).catch(() => {
    loading.value = false;
    // resetFields();
  });
  if (data?.data) {
    taskInfo.value = data?.data;
    // console.log('data?.data', mockData)
    // taskInfo.value = JSON.parse(JSON.stringify(mockData));
  }
  loading.value = false;
  // 模拟数据返回，调试使用（保留）
  // setTimeout(() => {
  // 	loading.value = false;
  // 	taskInfo.value = JSON.parse(JSON.stringify(mockData));
  // }, 500);
}

// 报废
const scrapBtn = (): void => {};
// 正常
const normalBtn = (): void => {};
</script>

<style lang="scss" scoped>
@import "@/static/css/standard_item.scss";

.ce45656 {
  color: #e45656;
}

.c53c21d {
  color: #53c21d;
}

.upload-scan {
  padding: $uni-page-padding;
  padding-top: 5px;
  padding-bottom: 1px;
  display: flex;
  align-items: center;

  // box-shadow: 0 1px 10px 0px rgb(19 10 236 / 10%);
  .u-icon {
    margin-left: 8px;
  }
}

.submit_btnTwo {
  margin: 0px 20rpx 16rpx 10rpx;
  font-size: 16px;
  height: 45px;
  line-height: 45px;
  box-shadow: 0 1px 10px rgb(3 121 255 / 30%);
}

.grey_btnTwo {
  margin: 0px 10rpx 16rpx 20rpx;
  font-size: 16px;
  height: 45px;
  line-height: 45px;
  border: 1px solid #ccc;
}

.submit_btn_divTwo {
  position: fixed;
  display: flex;
  align-items: center;
  width: 100%;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 10;

  uni-button {
    flex: 1;
    border-radius: 10px;
  }
}
</style>
